
$(() => {
  $('body').prepend(`<button id="yhby_gather" style="right: 400px; top: 10px">切换搬家账号<p id="yhby_gather_tips" class="tips">（暂未登陆）</p></button>`)

  // 点击切换至当前平台的用户账号
  $('#yhby_gather').click(function() {
    getAccountConfig()
  })

  // 监听页面切换 实时跟踪当前账号的平台
  chrome.extension.onMessage.addListener(
    function(req, sender, res) {
      if (req.action === 'getAccountPlatform') {
        $('#yhby_gather_tips').text(req.platform ? `（当前${req.platform}）` : '（暂未登陆）')
      }
    }
  )
  // 页面刷新时 获取当前账号的平台
  chrome.runtime.sendMessage({ cmd: 'getAccountPlatform' }, function(platform) {
    $('#yhby_gather_tips').text(platform ? `（当前${platform}）` : '（暂未登陆）')
  })

  function getAccountConfig() {
    // 获取当前账号的信息
    if ((/http(s):\/\/.+\.youboy.com\/seller/).test(location.href)) {
      let userInfo = getCookie('MS-UserInfo')
      if (userInfo !== null) {
        userInfo = JSON.parse(decodeURIComponent(userInfo))
        if (userInfo.factoryId && userInfo.factoryId > 0) {
          userInfo.authorization = decodeURIComponent(getCookie('MS-Token'))
          userInfo.platform = '直卖网'
          chrome.runtime.sendMessage({ userInfo, cmd: 'getGYPConfig', origin: location.origin, host: location.host }, function(platform) {
            $('#yhby_gather_tips').text(platform ? `（当前${platform}）` : '（暂未登陆）')
          })
        }
      }
    }
  }

  function getCookie(cname) {
    var name = cname + '='
    var ca = document.cookie.split(';')
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i].trim()
      if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
    }
    return null
  }

})
